﻿import VEdit from './EditContent.vue'
import VColumns from './SelectColumns.vue'
import VImport from './ImportData.vue'
import VTitle from '@/components/common/MainTitle.vue'
export default {
  data () {
    return {
      titleName: '',
      funUid: '',
      // 检索部分
      searchDialog: false,
      searchRuleForm: {},
      searchList: [],
      searchRules: {},
      // 表格部分
      ruleForm: {
        tableData: [],
        tableColumn: [],
        // 用于存储修改之前的数据
        ori_data: []
      },
      rules: {},
      // select的内容
      selectOptions: [],
      selectValue: {},
      showValue: {},
      // selectValue: '',
      // showValue: '',
      operationType: '',
      // 点击某一条数据时，弹框的部分
      editInfo: {
        item: {}
      },
      showEditDialog: false,
      editRow: '',
      totalData: [],
      // 页码部分
      totalLength: 0,
      currentPage: 1,
      pageSize: 10,
      // 导出模板或下载数据时，选择的栏位
      column_select: '',
      // 选择栏位的弹窗
      showColumnsDialog: false,
      exportType: '',
      loading: false,
      loadingText: '导出中',
      // 上传文件的弹窗
      showUploadDialog: false,
      // 更多操作按钮下自动生成的事件列表
      eventsList: [],
      // 表格每一行右侧操作按钮栏位下生成的行事件
      rowEventsList: []
    }
  },
  created () {
    this.init()
  },
  methods: {
    // 点击弹窗的取消按钮
    resetForm (forms) {
      this.$refs[forms].clearValidate()
      this.dialogFormVisible = false
    },
    closeDialog () {
      this.$refs.ruleForm.clearValidate()
    },
    // 初始化页面
    init () {
      this.funUid = this.$route.query.uid
      this.currentPage = 1
      this.pageSize = 10
      this.searchRuleForm = {}
      this.eventsList = []
      this.rowEventsList = []
      this.getFunInfo(this.funUid)
      this.getDetailInfo(this.pageSize, this.currentPage, this.searchRuleForm)
    },
    // 获取功能的设定信息---定义好表头及功能的基本信息
    getFunInfo (uid) {
      this.$get('/s_table/' + uid + '/info').then(data => {
        let dataInfo = data.data.result
        if (dataInfo.code === 'failed') {
          this.$message({
            message: dataInfo.msg,
            type: 'warning'
          })
        }
        if (dataInfo.code === 'success') {
          this.titleName = dataInfo.name
          // 生成表头
          this.ruleForm.tableColumn = dataInfo.columns
          this.getRules()
          // 搜索的部分
          this.searchList = dataInfo.search
          this.getSearchRules()
          // 获取普通事件
          this.eventsList = dataInfo.events.filter(val => {
            return val.at === 'New'
          })
          // 获取行事件
          this.rowEventsList = dataInfo.row_events.filter(val => {
            return val.at === 'New'
          })
        }
      }).catch(error => {
        console.log(error)
      })
    },
    // 生成表单的验证规则
    getRules () {
      if (this.ruleForm.tableColumn.length) {
        this.ruleForm.tableColumn.forEach(val => {
          if (val.ui_type !== 'RichText' && val.ui_type !== 'File' && val.ui_type !== 'Picture') {
            if (val.check_required) {
              this.rules[val.column_name] = [
                {required: true, message: val.column_name + '不能为空', trigger: 'blur'}
              ]
            }
            if (val.check_regex) {
              this.rules[val.column_name] = [
                {pattern: val.check_regex, message: '所填内容不满足要求', trigger: 'blur'}
              ]
            }
          }
        })
      }
    },
    // 打开检索的弹窗时
    openSearchDialog () {
      this.searchDialog = true
    },
    // 关闭检索的弹窗时
    closeSearchDialog () {
      this.$refs.searchRuleForm.clearValidate()
      this.searchDialog = false
    },
    // 获取检索的结果
    submitSearch (forms) {
      this.$refs[forms].validate((valid) => {
        if (valid) {
          this.$refs[forms].clearValidate()
          this.searchDialog = false
          this.getDetailInfo(this.pageSize, this.currentPage, this.searchRuleForm)
        } else {
          return false
        }
      })
    },
    // 获取检索的表单验证
    getSearchRules () {
      if (this.searchList.length) {
        this.searchList.forEach(pval => {
          if (pval.conditions.length) {
            pval.conditions.forEach(val => {
              if (val.ui_type !== 'RichText' && val.ui_type !== 'File' && val.ui_type !== 'Picture') {
                if (val.check_required) {
                  this.searchRules[val.parameter_name] = [
                    {required: true, message: val.column_name + '不能为空', trigger: 'blur'}
                  ]
                }
                if (val.check_regex) {
                  this.searchRules[val.parameter_name] = [
                    {pattern: val.check_regex, message: '所填内容不满足要求', trigger: 'blur'}
                  ]
                }
              }
            })
          }
        })
      }
    },
    // 获取功能的数据详细表----渲染表格
    getDetailInfo (limit, page, searchInfo) {
      let params = {
        limit: limit,
        page: page
      }
      if (searchInfo) {
        for (let key in searchInfo) {
          params[key] = searchInfo[key]
        }
      }
      this.operationType = ''
      this.$get('/s_table/' + this.funUid, params).then(data => {
        let dataInfo = data.data.result
        if (dataInfo.code === 'failed') {
          this.$message({
            message: dataInfo.msg,
            type: 'warning'
          })
        } else if (dataInfo.code === 'success') {
          this.totalData = JSON.parse(JSON.stringify(dataInfo.data))
          this.ruleForm.tableData = this.totalData
          // 该表数据的初始值
          this.ruleForm.ori_data = JSON.parse(JSON.stringify(dataInfo.data))
          // 页码相关的信息
          this.totalLength = dataInfo.total_count
          this.pageSize = dataInfo.limit
          this.currentPage = dataInfo.page
        }
      }).catch(error => {
        console.log(error)
      })
    },
    // 获取pop或者select的option
    getSelect (columnName) {
      this.$patch('/s_table/pop/' + this.funUid + '/' + columnName).then(data => {
        let dataInfo = data.data.result
        if (dataInfo.code === 'failed') {
          this.$message({
            message: dataInfo.msg,
            type: 'warning'
          })
        } else if (dataInfo.code === 'success') {
          this.$set(this.selectOptions, columnName, dataInfo.data)
          this.$set(this.selectValue, columnName, dataInfo.column_value)
          this.$set(this.showValue, columnName, dataInfo.column_show[0].column_name)
        }
      }).catch(error => {
        console.log(error)
      })
    },
    // 定义表头的信息
    handelHelp (h, {column}) {
      if (column.labelClassName) {
        return (
          <el-tooltip effect="dark" placement="top">
            <div slot='content'>{column.labelClassName}</div>
            <span>{column.label}</span>
          </el-tooltip>
        )
      } else {
        return (
          h('span', [column.label])
        )
      }
    },
    handelHelpKey (h, {column}) {
      if (column.labelClassName) {
        return (
          <el-tooltip effect="dark" placement="top">
            <div slot='content'>{column.labelClassName}</div>
            <span><span style="color:red">*</span>{column.label}</span>
          </el-tooltip>
        )
      } else {
        return (
          h('span', [
            h('span', {style: {color: 'red'}}, ['*']),
            h('span', [column.label])
          ])
        )
      }
    },
    // 编辑某一单元格的信息时
    editTableCloumn (item, row, index) {
      this.showEditDialog = true
      this.editInfo.item = item
      this.editInfo.row = row
      this.editInfo.status = 'edit'
      // 功能的uid
      this.editInfo.funUid = this.funUid
      this.editRow = index
    },
    // 查看某一单元格的信息时
    showTableCloumn (item, row, index) {
      this.showEditDialog = true
      this.editInfo.item = item
      this.editInfo.row = row
      this.editInfo.status = 'show'
      this.editInfo.funUid = this.funUid
      this.editRow = index
    },
    // 编辑成功返回的数据
    sureEdit (editContent) {
      this.showEditDialog = false
      this.ruleForm.tableData[this.editRow][this.editInfo.item.column_name] = editContent
    },
    // 删除单条数据时
    handleSingleDelete (row, index) {
      // 当为新增时移除新增项时
      if (this.operationType === 'add') {
        this.ruleForm.tableData.splice(index, 1)
      } else {
        this.submitDelete([row])
      }
    },
    // 提交删除的方法
    submitDelete (fromDelete) {
      this.$confirm('此操作将永久删除数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        cancelButtonClass: 'el-button--info'
      }).then(() => {
        this.$delete('/s_table/' + this.funUid, {
          data: {
            data: fromDelete
          }
        }).then(data => {
          if (data.status === 204) {
            this.$message({
              message: '数据删除成功',
              type: 'success'
            })
            // 需要重新渲染表格
            this.getDetailInfo(this.pageSize, this.currentPage, this.searchRuleForm)
          }
        }).catch(error => {
          console.log(error)
        })
      }).catch(() => {})
    },
    // 点击取消按钮时
    resetForm (forms) {
      this.$refs[forms].clearValidate()
      this.operationType = ''
      this.getDetailInfo(this.pageSize, this.currentPage, this.searchRuleForm)
    },
    // 向表中新增一条数据
    addData () {
      //  alert("待添加,弹出框");
      this.operationType = 'add'
      if (this.ruleForm.tableColumn.length) {
        let objExam = {}
        this.ruleForm.tableColumn.forEach(val => {
          let index = val.column_name
          if (val.ui_type === 'Switch') {
            objExam[index] = false
          } else {
            objExam[index] = ''
          }
        })
        objExam.newData = 'newData'
        this.ruleForm.tableData.unshift(objExam)
      }
    },
    // 提交新增的方法
    submitAdd () {
      if (this.ruleForm.tableData.length) {
        let newArry = []
        this.ruleForm.tableData.forEach(val => {
          // 在表格中所有的数据中，找到新增的数据
          if (val.newData === 'newData') {
            // 将新增数据中的 newData 属性和值去掉并保存到新的数组中
            let objExam = {}
            for (let key in val) {
              if (key !== 'newData') {
                objExam[key] = val[key]
              }
            }
            newArry.push(objExam)
          }
        })
        if (newArry.length) {
          this.$post('/s_table/' + this.funUid, {
            data: newArry
          }).then(data => {
            if (data.data.result.code === 'success') {
              this.$message({
                message: '添加数据成功！',
                type: 'success'
              })
              // 重新渲染表格
              this.getDetailInfo(this.pageSize, this.currentPage)
            } else if (data.data.result.code === 'failed') {
              this.$message({
                message: data.data.result.msg,
                type: 'warning'
              })
            }
          }).catch(error => {
            console.log(error)
          })
        } else {
          this.$message({
            message: '该功能的数据详情表中还没有新增的数据，不需要提交',
            type: 'warning'
          })
        }
      } else {
        this.$message({
          message: '该功能的数据详情表中还没有数据，不需要提交',
          type: 'warning'
        })
      }
    },
    // 点击右侧的编辑按钮时
    editData () {
      if (this.ruleForm.tableData.length) {
        this.operationType = 'edit'
      } else {
        this.$message({
          message: '该功能的数据详情表还没有数据，无法进行编辑操作',
          type: 'warning'
        })
      }
    },
    // 提交编辑的方法
    submitEdit () {
      let changeInfo = this.justifyChangeData()
      this.$patch('/s_table/' + this.funUid, {
        ori_data: changeInfo.oriData,
        data: changeInfo.changedData
      }).then(data => {
        if (data.data.result.code === 'success') {
          this.$message({
            message: '编辑数据成功',
            type: 'success'
          })
          this.getDetailInfo(this.pageSize, this.currentPage, this.searchRuleForm)
        } else if (data.data.result.code === 'failed') {
          this.$message({
            message: data.data.result.msg,
            type: 'warning'
          })
        }
      }).catch(error => {
        console.log(error)
      })
    },
    // 判断编辑的数据
    justifyChangeData () {
      let changeInfo = {
        oriData: [],
        changedData: []
      }
      this.totalData.forEach((val, index) => {
        let hadChanged = false
        this.ruleForm.tableColumn.forEach(columnVal => {
          if (val[columnVal.column_name] !== this.ruleForm.ori_data[index][columnVal.column_name]) {
            hadChanged = true
          }
        })
        if (hadChanged) {
          changeInfo.oriData.push(this.ruleForm.ori_data[index])
          changeInfo.changedData.push(val)
        }
      })
      return changeInfo
    },
    // 点击确定提交的按钮时
    submitForm (forms, submitType) {
      this.$refs[forms].validate((valid) => {
        if (valid) {
          if (submitType === 'edit') {
            this.submitEdit()
          } else if (submitType === 'add') {
            this.submitAdd()
          }
        } else {
          return false
        }
      })
    },
    // 底部页码的部分
    handleSizeChange (val) {
      this.pageSize = val
      this.getDetailInfo(this.pageSize, this.currentPage, this.searchRuleForm)
    },
    handleCurrentChange (val) {
      this.currentPage = val
      this.getDetailInfo(this.pageSize, this.currentPage, this.searchRuleForm)
    },
    // 右侧的更多操作部分
    handleCommand (command) {
      if (command === 'downloadTem') {
        this.showColumnsDialog = true
        this.exportType = 'downloadTem'
      } else if (command === 'downloadData') {
        this.showColumnsDialog = true
        this.exportType = 'downloadData'
      } else if (command === 'importData') {
        this.showUploadDialog = true
      } else {
        if (command.rowData) {
          this.eventsEval(command.eventsNo, btoa(encodeURIComponent(command.rowData)))
        } else {
          this.eventsEval(command.eventsNo, '')
        }
      }
    },
    // 事件触发时执行的方法
    eventsEval (eventNo, rowData) {
      this.$post('/s_table/' + this.funUid + '/event/' + eventNo + '/eval', {
        this_data: rowData
      }).then(data => {
        if (data.data.result.code === 'success') {
          this.$message({
            message: data.data.result.msg,
            type: 'success'
          })
        } else if (data.data.result.code === 'failed') {
          this.$message({
            message: data.data.result.msg,
            type: 'error'
          })
        }
      }).catch(error => {
        console.log(error)
      })
    },
    // 确定选择栏位时
    sureSelectColumns (data) {
      this.showColumnsDialog = false
      this.loading = true
      // 判断检索的内容
      let searchString = ''
      let searchArray = []
      if (this.searchRuleForm) {
        for (let key in this.searchRuleForm) {
          searchArray.push(key + '=' + this.searchRuleForm[key])
        }
        searchString = searchArray.join('&')
      } else {
        searchString = ''
      }
      // 处理选择的栏位信息
      if (data.length) {
        let arr = []
        data.forEach(val => {
          arr.push(val.column_name)
        })
        this.column_select = arr.join()
      } else {
        this.column_select = ''
      }
      // 执行下载的操作
      if (this.exportType === 'downloadTem') {
        this.exportTem('/export_template')
      } else if (this.exportType === 'downloadData') {
        this.exportTem('/export', searchString)
      }
    },
    // 下载模板
    exportTem (routerName, searchString) {
      let searchInfo = ''
      if (searchString) {
        searchInfo = '?' + searchString
      } else {
        searchInfo = ''
      }
      this.$post('/s_table/' + this.funUid + routerName + searchInfo, {
        column_select: this.column_select
      }).then(data => {
        this.loading = false
        let dataInfo = data.data.result
        if (dataInfo.code === 'success') {
          let content = decodeURIComponent(dataInfo.file)
          let blobContent = this.toBlob(content, dataInfo.filetype)
          this.downloadblob(blobContent, dataInfo.filename)
        } else if (dataInfo.code === 'failed') {
          this.$message({
            message: dataInfo.msg,
            type: 'error'
          })
        }
      }).catch(error => {
        console.log(error)
      })
    },
    // 下载文件
    downloadblob (blobcontent, filename) {
      if ('msSaveOrOpenBlob' in navigator) {
        // Microsoft Edge and Microsoft Internet Explorer 10-11
        window.navigator.msSaveOrOpenBlob(blobcontent, filename)
      } else {
        // 创建隐藏的可下载链接
        var eleLink = document.createElement('a')
        eleLink.download = filename
        eleLink.style.display = 'none'
        // 字符内容转变成blob地址
        eleLink.href = URL.createObjectURL(blobcontent)
        // 触发点击
        document.body.appendChild(eleLink)
        eleLink.click()
        // 然后移除
        document.body.removeChild(eleLink)
      }
    },
    // 转为base64
    toBlob (base64str, filetype) {
      let bytes = window.atob(base64str)
      let n = bytes.length
      let u8arr = new Uint8Array(n)
      while (n--) {
        u8arr[n] = bytes.charCodeAt(n)
      }
      return new Blob([u8arr], {type: filetype})
    },
    // 关闭上传文件的弹窗
    closeUploadDialog () {
      this.showUploadDialog = false
    }
  },
  components: {
    VEdit, VImport, VColumns, VTitle
  }
}
